package com.snc.controller.app;

import com.snc.controller.index.BaseController;
import com.snc.entity.*;
import com.snc.exception.BusinessException;
import com.snc.plugin.Result;
import com.snc.plugin.Status;
import com.snc.util.Md5Utils;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/5/20 0020.
 */
@Controller
@RequestMapping("/app/resident/")
public class ResidentController extends BaseController {

    

    /**
     * 注册
     *
     * @return
     */
    @ResponseBody
    @Transactional(readOnly = false)
    @RequestMapping(method = RequestMethod.POST, value = "reg")
    public Result reg() {

        ResidentFormMap resident = super.toFormMap(ResidentFormMap.class);

        //查询该手机号码是否已注册
        List<ResUserFormMap> results = new ResidentFormMap().findByAttribute("phone", resident.get("phone"));
        if (results != null && results.size() > 0) {
            throw new BusinessException("该手机号码已注册，请直接登录");
        }

        
        String password = resident.getStr("password");
        password=Md5Utils.string2MD5(password);
        resident.put("password", password);
        resident.put("createTime", new Date());
        resident.put("isAuth", Status.N);
       

        try {
            resident.save();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.Null();
    }

    /**
     * 找回密码
     *
     * @return
     */
    @ResponseBody
    @Transactional(readOnly = false)
    @RequestMapping(method = RequestMethod.POST, value = "findPwd")
    public Result findPwd() throws Exception {

        ResidentFormMap resident = super.toFormMap(ResidentFormMap.class);

        //查询该手机号码是否已注册
        List<ResidentFormMap> results = new ResidentFormMap().findByAttribute("phone", resident.get("phone"));
        if (results == null || results.size() == 0) {
            throw new BusinessException("该手机号码未注册");
        }



        resident.put("id", results.get(0).get("id"));
        //修改密码
        resident.update();

        return Result.Null();
    }


    /**
     * 登录
     *
     * @return
     */
    @ResponseBody
    @Transactional(readOnly = false)
    @RequestMapping(method = RequestMethod.POST, value = "login")
    public Result login(String phone, String password, String deviceName,String isMaster, HttpServletRequest request) throws Exception {

        //根据手机号查询该用户
        List<ResidentFormMap> results = new ResidentFormMap().findByAttribute("phone", phone);
        if (results == null || results.size() == 0) {
            throw new BusinessException("该用户还未注册");
        }

        ResidentFormMap resident = results.get(0);
        if(!resident.getStr("isMaster").equals(isMaster)){
            throw new BusinessException("用户密码错误");
        }

        String handledPwd = resident.getStr("password");
       
        
        if (!handledPwd.equals(password)) {
            throw new BusinessException("用户密码错误");
        }
        
        int id = resident.getInt("id");
        String token=Md5Utils.string2MD5(id+"");
        resident.put("token", token);
        resident.update();
        //此处开始记录登录日志
        ResidentLoginLogFormMap log = new ResidentLoginLogFormMap();
        log.put("userId", resident.get("id"));
        log.put("loginTime", new Date());
        log.put("deviceName", deviceName);
        log.put("ip", request.getRemoteAddr());
        log.save();


        return Result.Success(resident);
    }

    /**
     * 修改个人信息，包含id，name，地址。
     *
     * @return 结果
     * @throws Exception
     */
    @ResponseBody
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "updateInfo")
    public Result updateInfo() throws Exception {
        ResidentFormMap resident = super.toFormMap(ResidentFormMap.class);
        resident.update();
        return Result.Null();
    }

    /**
     * 获取个人信息
     *
     * @return 结果
     * @throws Exception
     */
    @ResponseBody
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "info")
    public Result info(String id) {
        ResidentFormMap resident = new ResidentFormMap();
        resident.put("id", id);
        resident = resident.findbyFrist();
        if(resident.getLong("school") != null){
            SchoolFormMap map = new SchoolFormMap();
           List<SchoolFormMap> list =  map.findByAttribute("id",resident.getLong("school"));
            resident.put("schoolName",list.get(0).getStr("name"));
        }

        return Result.Success(resident);
    }



    /**
     * 获取个人信息
     *
     * @return 结果
     * @throws Exception
     */
    @ResponseBody
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "getByPhone")
    public Result getByPhone(String phone) {
        ResidentFormMap resident = new ResidentFormMap();
        resident.put("phone", phone);
        resident.put("isMaster","N");
        resident = resident.findbyFrist();
        return Result.Success(resident);
    }

    /**
     * 认证
     *
     * @return
     */
    @ResponseBody
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/auth")
    public Result add(HttpServletRequest request,   MultipartFile image) throws Exception {

        ResidentFormMap user = super.toFormMap(ResidentFormMap.class);
        user.put("id", request.getParameter("id"));
        user.put("isAuth","Z");
        String root = request.getSession().getServletContext().getRealPath("");

        //取得上传文件
        MultipartFile file = image;
        if (file != null) {
            //取得当前上传文件的文件名称
            String myFileName = file.getOriginalFilename();
            String suffix = myFileName.substring(myFileName.lastIndexOf(".") + 1);
            //如果名称不为“”,说明该文件存在，否则说明该文件不存在
            if (myFileName.trim() != "") {
                //重命名上传后的文件名
                String fileName = UUID.randomUUID().toString() + "." + suffix.toLowerCase();

                //文件夹路径
                String filePath = root + "/cdn/teacher/";
                File f = new File(filePath);
                // 目录已存在创建文件夹
                if (!f.exists()) {
                    f.mkdirs();// 目录不存在的情况下，会抛出异常
                }

                //定义上传路径
                String path = filePath + fileName;
                //创建文件
                File localFile = new File(path);
                file.transferTo(localFile);

                String name = "/ROOT/cdn/teacher/" + fileName;
                user.put("image", name);
                user.update();

            }
        }

        return Result.Null();
    }

    /**
    * 上传头像
    *
    * @return
    */
   @ResponseBody
   @Transactional
   @RequestMapping(method = RequestMethod.POST, value = "/header")
   public Result header(HttpServletRequest request,   MultipartFile image) throws Exception {

       ResidentFormMap user = super.toFormMap(ResidentFormMap.class);
       user.put("id", request.getParameter("id"));
      
       String root = request.getSession().getServletContext().getRealPath("");

       //取得上传文件
       MultipartFile file = image;
       if (file != null) {
           //取得当前上传文件的文件名称
           String myFileName = file.getOriginalFilename();
           String suffix = myFileName.substring(myFileName.lastIndexOf(".") + 1);
           //如果名称不为“”,说明该文件存在，否则说明该文件不存在
           if (myFileName.trim() != "") {
               //重命名上传后的文件名
               String fileName = UUID.randomUUID().toString() + "." + suffix.toLowerCase();

               //文件夹路径
               String filePath = root + "/header/";
               File f = new File(filePath);
               // 目录已存在创建文件夹
               if (!f.exists()) {
                   f.mkdirs();// 目录不存在的情况下，会抛出异常
               }

               //定义上传路径
               String path = filePath + fileName;
               //创建文件
               File localFile = new File(path);
               file.transferTo(localFile);

               String name = "/ROOT/header/" + fileName;
               user.put("header", name);
               user.update();

           }
       }

       return Result.Null();
   }

}
